<!--
 * @Author: 刘金开 liujinkai@jiankeyan.com
 * @Date: 2023-07-11 22:44:11
 * @LastEditors: 刘金开 liujinkai@jiankeyan.com
 * @LastEditTime: 2023-08-07 11:48:12
 * @FilePath: \font\src\view\class.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<div>
		<el-card class="boxCard" :body-style="{ padding: '10px 10px 5px' }" >
				<div class="title" >
		<div class="mt-4" style=" display: inline-block;">
		<el-input v-model="input3" placeholder="请输入班级名称或根据专业查询" :clearable="true"  class="input-with-select" style="width: 500px; "  
					size="large">
			<template #prepend>
			<el-select v-model="select" placeholder="请选择专业" size="large" clearable="true" style="width: 120px">
			
				<el-option v-for="(item, index) in filteredArray" :key="index" :label="item.label" :value="item.value"></el-option>
			</el-select>
			</template>
			<template #append>
			<el-button  type="primary" text @click="searchFor">
     
         <el-icon><Search /></el-icon>
        </el-button>
			<!-- <el-button class="button" size="large" text >Operation button</el-button> -->
			</template>
		</el-input>
		</div>
		<div style=" display: inline-block;">
		<!-- <el-button type="primary" class="button"  size="large" text @click="getSpecialList">全部</el-button> -->
		
		<el-button text type="primary" size="large" @click="addClassClick">新增班级</el-button>
		
		<el-button text type="primary" size="large" @click="manyDelClick(arr)">批量删除</el-button>
	

          <el-button  class="iconBox" type="primary" text @click="refresh">
        <el-icon class="hoverIcon"><RefreshRight /></el-icon>
        </el-button>
        <el-button text type="primary" size="large" @click="exportDownloadClick">导出下载</el-button>
		</div>
	</div>
	<!-- 表格 -->
	<div >
    <el-table
    id="tableId"
    border="true"
  :data="dataList"
  style="width: 100%; "
  max-height="554px"
 :highlight-current-row="true"
 :row-style="{height: '30px'}"
  @selection-change="selectionChange"
 >
 <el-table-column type="selection" width="35" />
  <el-table-column type="index" width="50"   align="center" />
  <el-table-column fixed prop="id" label="专业id" width="50" v-if="false" />
  <el-table-column fixed prop="specialityID" label="专业id" width="50" v-if="false" />
    <el-table-column prop="name" label="班级名称" width="100"  align="center"  :show-overflow-tooltip="true"/>
    <el-table-column prop="classTimeStart" label="开课时间"  align="center" width="120" />
    <el-table-column prop="classTimeEnd" label="放学时间"  align="center" width="140" />
    	<el-table-column prop="specialityName" label="所属专业" width="100"  align="center" />
  <el-table-column prop="created_at" label="创建时间"  align="center" width="120" />
    <el-table-column prop="updated_at" label="更新时间"  align="center" width="120" />
    <el-table-column prop="enable" header-align="center"  label="正在开设"   align="center" width="90">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enable === false">否</el-tag>
            <el-tag type="success" v-else-if="scope.row.enable === true">是</el-tag>
          </template>
        </el-table-column>
    <el-table-column prop="note" label="备注" width="310"   align="center" :show-overflow-tooltip="true"/>
    <el-table-column fixed="right" label="操作" width="120"  align="center">
      <template   #default="scope">
        <el-button link type="primary" size="small" @click="editClick(scope)"
          >编辑</el-button
        >
        <el-button link type="danger" size="small" @click="handleDelete(scope.$index,scope)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
  </div>

      <!-- el-dialog 新增-->
	  <el-dialog 
  v-model="showAddPage" 
  title="新增班级" 
  :modal="false"
  width="60%" 
   center>

   <el-form
   ref="ruleForms"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :inline="true"
    :size="formSize"
    status-icon
  >
    <el-form-item label="专业名称"  prop="name" >
      <el-input v-model="ruleForm.name"  placeholder="请输入专业名称 " />
    </el-form-item>

    <el-form-item label="正在开设" prop="enable">
      <el-radio-group v-model="ruleForm.enable">
        <el-radio :label="true" border >是</el-radio>
      <el-radio :label="false" border>否</el-radio>
      </el-radio-group>
    </el-form-item>

    
    <el-form-item label="请选择时间" prop="classTimeStart">
    <el-row :gutter="80">
      <el-col :span="7">
        <el-time-picker v-model="ruleForm.classTimeStart" placeholder="开课时间" />
     
      </el-col>
      <el-col :span="7" :offset="6">
       <el-form-item  prop="classTimeEnd" label-width="80px" style="margin-left: 9px;">
        <el-time-picker v-model="ruleForm.classTimeEnd" placeholder="下课时间" />
       </el-form-item>
      </el-col>
    </el-row>
      </el-form-item>
    <el-row  :gutter="80">
      <el-col :span="7">
              <el-form-item  label="所属专业" prop="specialityID" >
              <el-select v-model="ruleForm.specialityID "  :clearable="true"  class="m-2" placeholder="请选择该班级所属专业"  >
              <el-option
                v-for="item in filteredArray"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            </el-form-item>
      </el-col >

        <el-col :span="7"  :offset="4">
            <el-form-item label="备注"  prop="note" label-width="40px" >
            <el-input v-model="ruleForm.note"  placeholder="可在此处添加备注信息哦"  />
            </el-form-item>
        </el-col>
    </el-row>

    
   

 
 
 <el-row type="flex" justify="center">
	   
    <el-form-item >
        <el-button @click="showAddPage=false">取消</el-button>
      <el-button type="primary" @click="submitForm()">
        确认
      </el-button>

    </el-form-item>
 </el-row>
  </el-form>

  

  </el-dialog>

<!-- 编辑 -->
<el-dialog 
  v-model="showEditPage" 
  title="编辑班级" 
  :modal="false"
  width="60%" 
   center>

   <el-form
   ref="ruleForms"
    :model="editForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :inline="true"
    status-icon
  >
    <el-form-item label="专业名称"  prop="name" >
      <el-input v-model="editForm.name"  placeholder="请输入专业名称 " />
    </el-form-item>

    <el-form-item label="正在开设" prop="enable">
      <el-radio-group v-model="editForm.enable">
        <el-radio :label="true" border >是</el-radio>
      <el-radio :label="false" border>否</el-radio>
      </el-radio-group>
    </el-form-item>

    
    <el-form-item label="请选择时间" prop="classTimeStart">
    <el-row :gutter="80">
      <el-col :span="7">
        <el-time-picker
         v-model="editForm.classTimeStart" 
          placeholder="开课时间" 
           this.ruleForm.date
           format="HH:mm:ss"
          />
     
      </el-col>
      <el-col :span="7" :offset="6">
       <el-form-item  prop="classTimeEnd" label-width="80px" style="margin-left: 9px;">
        <el-time-picker 
        v-model="editForm.classTimeEnd"
         placeholder="下课时间" 
         format="HH:mm:ss"
         
         />
       </el-form-item>
      </el-col>
    </el-row>
      </el-form-item>
      
    <el-row  :gutter="80">
      <el-col :span="7">
              <el-form-item  label="所属专业" prop="specialityID"  >
              <el-select v-model="editForm.specialityID" class="m-2"  :clearable="true" placeholder="请选择该班级所属专业"  >
              <el-option
                v-for="item in filteredArray"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            </el-form-item>
      </el-col >

        <el-col :span="7"  :offset="4">
            <el-form-item label="备注"  prop="note" label-width="40px" >
            <el-input v-model="editForm.note"  placeholder="可在此处添加备注信息哦"  />
            </el-form-item>
        </el-col>
    </el-row>

    
   

 
 
 <el-row type="flex" justify="center">
	   
    <el-form-item >
        <el-button @click="showEditPage=false">取消</el-button>
      <el-button type="primary" @click="submitEditForm()">
        确认
      </el-button>

    </el-form-item>
 </el-row>
  </el-form>

  

  </el-dialog>

  <!-- 分页器 -->
  <div class="pageNation">
			<pagination   
      :pageSize="pageResult.pageSize"

		:pageTotal="allPages"
			@pageFunc="pageFunc">
		</pagination>
		</div>
		</el-card>

	</div>
</template>

<script setup>
 import {getSpecialAll,addSpecial,editSpecial,deleteSpecial,getSpecialOne} from "../services/api/speciality.js";
import {getClass,editClass,createClass,deleteClass,} from "../services/api/class.js"; 
import {onMounted, reactive, ref, toRaw,nextTick ,watch, onBeforeMount,toRefs  } from "vue";
import { ElMessageBox,ElNotification } from 'element-plus'
import{ exportDownload}from '../utils/exportExcel'
import pagination from '../components/pageNation.vue'

import {
    Message,
    Setting,
    Document,
    Memo,
    Reading,
    Star,
    User,
    Postcard,
    School,
    List,
    ElementPlus,
    Flag,
    Ticket,
    Platform,
    Expand, Fold,
    Search,
    RefreshRight
} from '@element-plus/icons-vue';

const list = ref()
const input3=ref('');
const dataList = ref([]);
const allPages=ref()
const showAddPage=ref(false);
const ruleForms = ref(null);  
const arr = ref([]);
const arrs = ref([]);
const select=ref(0)
const showEditPage=ref(false)
const pageResult = reactive({
        // 放置页码及相关数据
        page: 1, //当前页
        pageSize: 20, //每页条目数
        specialityID:0,
        name:'',
      });  
      // 获取所有的专业id和名字所传参数
const specialIdAll = reactive({
        // 放置页码及相关数据
        page: 1, //当前页
        pageSize: 100, //每页条目数
      });
// 编辑表单绑定数据
      const editForm=reactive({
          id:'',
          name: '',
          enable: false,
          note: '',
          specialityID:'',
          classTimeEnd:'',
          classTimeStart:'',
        })
// const List=ref()
const filteredArray=ref()
// 导出表格名称
const excelName=ref('班级信息')
      // 表单验证
const rules = reactive({
          name: [
            { required: true, message: '请输入班级名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度2到10个字符', trigger: 'blur' },
          ],

          enable: [
            {
              required: true,
              message: 'Please pick a option',
              trigger: 'change',
            },
          ],
          note: [
            {
              message: 'Please select activity resource',
              trigger: 'blur',
            },
          ],
          classTimeStart: [
            {
              type: 'date',
              required: true,
              message: 'Please pick a date',
              trigger: 'change',
            },
          ],
          classTimeEnd: [
            {
              type: 'date',
              required: true,
              message: 'Please pick a time',
              trigger: 'change',
            },
          ],
          specialityID:[
          {
              required: true,
              message: '请选择所属专业',
              trigger: 'change',
            },
          ]
        })
// 新增班级     表单绑定数据
  const ruleForm = reactive({
          
          name: '',
          enable: false,
          note: '',
          specialityID:85,
          classTimeEnd: '',
          classTimeStart: '' ,
        })
 // 编辑班级
      const editClick = (scope) => {
       showEditPage.value=true 
        // Object.assign(editForm,scope.row) 
        editForm.name= scope.row.name
        editForm.note= scope.row.note
         editForm.id= scope.row.id
         editForm.specialityID =scope.row.specialityID
         const [hours, minutes, seconds] = scope.row.classTimeStart.split(':');
         const [hour, minute, second] = scope.row.classTimeEnd.split(':');
         editForm.classTimeEnd = new Date(2023,7,20,hour,minute,second)
         editForm.classTimeStart = new Date(2023,7,20,hours,minutes,seconds)
        if(scope.row.enable==true){
          editForm.enable= true
        }else{
          editForm.enable= false
        }
      };


// 编辑确定
   const submitEditForm=()=>{    
   
    editForm.classTimeStart=editForm.classTimeStart.toISOString();
    editForm.classTimeEnd=editForm.classTimeEnd.toISOString();
    editClass(editForm).then((res)=>{
          showEditPage.value=false
          if(res.data.msg=='OK'){
            getClassList()
            ElNotification({
                                    title: 'Success',
                                    message: '编辑班级成功',
                                    type: 'success',
                                      })
          }else{
            ElNotification({
                                      title: 'Error',
                                      message: '编辑班级失败',
                                      type: 'error',
                          })
          }
        })
        
       
      }
  // 新增弹窗控制按钮
 const addClassClick = () => {
        showAddPage.value=true

      };
// 获取班级列表接口调用
const getClassList=async () => {
        const res = await getClass(pageResult)
        dataList.value = res.data.data.classes;

        allPages.value= res.data.data.count

      };
// 右上角刷新
const refresh=()=>{
  getClassList();

}
// 新增班级
     const submitForm= ()=>{
        ruleForms.value.validate((valid) => {
        if (valid) {

          createClass(ruleForm).then((res)=>{
            const { name } = toRefs(ruleForm); 
                              if(res.data.code === 200){
                                  showAddPage.value=false
                                  nextTick(() => {
                                      ruleForms.value.resetFields();
                                                  });  
                                  ElNotification({
                                    title: 'Success',
                                    message: `成功新增--${name.value}`,
                                    type: 'success',
                                      })
                                      getClassList();
                        }else{
                                    ElNotification({
                                      title: 'Error',
                                      message: `新增--${name.value}失败`,
                                      type: 'error',
                          })
                        }
                  })

        }})
      
      }
// 获取专业id和名称
      const getSpecialList = async () => {
        const res = await getSpecialAll(specialIdAll)
        list.value = res.data.data.specialities;
        filteredArray.value = list.value.map(obj => ({ value: obj.id, label: obj.name }));
        filteredArray.value.unshift({value: 0,label:'班级查询' });
      };

                  // 单个删除班级
                  const Delete = (index,scope) => {
                    let id=scope.row.id
                    let classname=scope.row.name
                  
                    arr.value=[]
                  
                      arr.value=[...arr.value,id]
                    deleteClass(arr.value).then((res)=>{
                          if(res.data.msg=='OK'){
                          dataList.value.splice(index, 1)
                          arr.value=[]
                          ElNotification({
                                                  title: 'Success',
                                                  message: `成功删除--${classname}`,
                                                  type: 'success',
                                                    })
                          }else{
                          ElNotification({
                                                    title: 'Error',
                                                    message: `删除--${classname}失败`,
                                                    type: 'error',
                                        })
                        }
                        
                      })
                    
                    
                    
                    }
      const handleDelete = (index,scope) =>{
            ElMessageBox.confirm(
                `确认删除?  >>> ${scope.row.name}`,
                'Warning',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
               
                    let id=scope.row.id
                    let classname=scope.row.name
                  
                    arr.value=[]
                  
                      arr.value=[...arr.value,id]
                    deleteClass(arr.value).then((res)=>{
                          if(res.data.msg=='OK'){
                          dataList.value.splice(index, 1)
                          arr.value=[]
                          ElNotification({
                                                  title: 'Success',
                                                  message: `成功删除--${classname}`,
                                                  type: 'success',
                                                    })
                          }else{
                          ElNotification({
                                                    title: 'Error',
                                                    message: `删除--${classname}失败`,
                                                    type: 'error',
                                        })
                        }
                        
                      })
 
                    
                })
                .catch(() => {
                    ElNotification({
                        title: '撤销删除',
                        type: 'info',
                        message: 'deleted canceled',
                    })
                })
        }
// 批量删除拿到id
    const selectionChange=(selection)=>{
                        arrs.value=[] 
                      
                let params = JSON.parse(JSON.stringify(selection));              
                        for( let i=0;i<params.length;i++ ){
                          arrs.value.push(params[i].id)
                        }
                        arr.value = [...new Set(arrs.value)];
                                                  
      }
//  批量删除班级
          const manyDelClick=(val)=>{
            deleteClass(val).then((res)=>{
            if(res.data.msg=='OK'){
              getClassList();
             arrs.value=[]
             ElNotification({
                                    title: 'Success',
                                    message: '批量删除成功',
                                    type: 'success',
                                      })
            }
           
        })
      }
         // 查询
const searchFor=()=>{
        let params={
          page:1,
          pageSize:5,
          name:input3.value,
          specialityID:select.value,
        }
         getClass(params).then((res)=>{
          dataList.value = res.data.data.classes;
          allPages.value= res.data.data.count
        })

      }

// 导出下载
const exportDownloadClick=( ()=>{
  pageResult.pageSize = allPages.value;
  getClass(pageResult).then( async(res)=>{
  dataList.value = res.data.data.classes;
  nextTick(() => {
    exportDownload(excelName.value,)
  });
})
})

watch(input3, (newValue) => {
      if (newValue === '') {
        getClassList()
      }
    });

    watch(dataList, (newArr) => {
  newArr.forEach((obj) => {
    obj.created_at = obj.created_at.slice(0, 10);
    obj.updated_at = obj.updated_at.slice(0, 10);
    obj.classTimeStart = obj.classTimeStart.slice(11, 19);
    obj.classTimeEnd = obj.classTimeEnd.slice(11, 19);
  });
});

// 分页函数
const pageFunc = (data) => {
 
        pageResult.pageSize = data.pageSize;
        pageResult.page = data.pageNum;
        getClassList();  // 触发获取数据函数
      };
onBeforeMount(()=>{
  getClassList();
})
	  onMounted(()=>{
    getSpecialList()
})
</script>
<style scoped>
.m-2{
width: 150px;
}
svg {
  width: 20px;
  height: 20px;

}
.iconBox{
  position: fixed;
  right: 10px;
  
}


</style>